Exercises
Video playback speed
In the sandbox below, we have a <VideoPlayer>
component that includes a playback speed control. Unfortunately, it doesn't work!
For context, here's how we can affect the playback speed of a <video>
element in vanilla JavaScript:
const videoElement = document.querySelector('#some-video');videoElement.playbackRate = 2; // Play at 2x speed
Acceptance Criteria:
- When the user changes the "Playback speed" control and then plays the corresponding video, that video should play at the selected speed.
- You should use the
useRef
hook to capture a ref to the<video>
element.
Code Playground
import React from 'react';
function VideoPlayer({ src, caption }) {
const playbackRateSelectId = React.useId();
return (
<div className="video-player">
<figure>
<video
controls
src={src}
/>
<figcaption>
{caption}
</figcaption>
</figure>
<div className="actions">
<label htmlFor={playbackRateSelectId}>
Select playback speed:
</label>
<select
id={playbackRateSelectId}
defaultValue="1"
>
<option value="0.5">0.5</option>
<option value="1">1</option>
<option value="1.25">1.25</option>
<option value="1.5">1.5</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</div>
);
}
export default VideoPlayer;
Solution:
Media Player
Let's build a media player!
The UI is ready, and we've loaded an audio file using an <audio>
tag. Our job now is to capture a reference to that element, and to trigger it when the user clicks the play/pause button.
For context, here's how we'd solve this problem in vanilla JS:
const audioElement = document.querySelector('#some-audio-elem');
// Start playing the song:audioElement.play();
// Stop playing it:audioElement.pause();
Acceptance Criteria:
- Clicking the “Play” button should start playing the song.
- Clicking the button again should pause the song.
- By default, we should render a
<Play>
icon inside the button, but it should flip to a<Pause>
icon while the song is playing.
Code Playground
import React from 'react';
import { Play, Pause } from 'react-feather';
import VisuallyHidden from './VisuallyHidden';
function MediaPlayer({ src }) {
return (
<div className="wrapper">
<div className="media-player">
<img
alt=""
src="https://sandpack-bundler.vercel.app/img/take-it-easy.png"
/>
<div className="summary">
<h2>Take It Easy</h2>
<p>Bvrnout ft. Mia Vaile</p>
</div>
<button>
<Play />
<VisuallyHidden>
Toggle playing
</VisuallyHidden>
</button>
<audio src={src} />
</div>
</div>
);
}
export default MediaPlayer;
Solution: